package com.right.handler;

import com.right.command.CsCommand;
import com.right.db.Bicycle;
import com.right.factory.NodeStatus;
import com.right.mapper.BicycleMapper;
import com.right.mapper.CommonMapper;
import com.right.mapper.UnlockMapper;
import com.right.util.push.PushUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by ding on 2019/1/22.
 */
@Slf4j
public class NormalCardUnlockHandler implements PackageHandler{
    private final UnlockMapper unlockMapper;
    private final BicycleMapper bicycleMapper;
    private final CommonMapper commonMapper;

    public NormalCardUnlockHandler(UnlockMapper unlockMapper, BicycleMapper bicycleMapper, CommonMapper commonMapper) {
        this.unlockMapper = unlockMapper;
        this.bicycleMapper = bicycleMapper;
        this.commonMapper = commonMapper;
    }

    @Override
    public boolean applies(List<String> dataList) {
        return CsCommand.NORMAL_CARD_UNLOCK.equals(dataList.get(0));
    }

    @Override
    public boolean handleMessage(ChannelHandlerContext ctx, List<String> dataList) {
        log.info("公交卡一卡通开锁");
        String lockNo = ctx.channel().attr(NodeStatus.LOCK_NO).get();
        String cardNo = dataList.get(1);
        Example o = new Example(Bicycle.class);
        o.createCriteria().andEqualTo("lockNo",lockNo);
        int i = bicycleMapper.selectCountByExample(o);
        if (i!= 1){
            log.error("未找到设备记录");
            return false;
        }else {
            //查找站点编号
            Map<String,Object> bicycleMap =  unlockMapper.selectBicycleByLockNo(lockNo);
            String dockSiteNo = (String)bicycleMap.get("docksiteno");
            Long operatorId = (Long)bicycleMap.get("operator_id");
            Integer bicycleStatus = (Integer)bicycleMap.get("bicycle_status");
            String bicycleNo = (String)bicycleMap.get("bicycle_no");
            Long bicycleId = (Long)bicycleMap.get("id");
            Long dockSiteId = (Long) bicycleMap.get("docksiteid");
            if (bicycleStatus != 1 && bicycleStatus != 8){
                log.error("自行车状态不正确");
                //0待投放1可租2骑行3维修4报废5车辆故障6带回7维修完成8临停
                return false;
            }
            //获取费用信息
            int count =  unlockMapper.selectCountBicycleChargerule(String.valueOf(operatorId));
            if (count !=1){
                log.error("未找到费用记录");
                return false;
            }
            BigDecimal timeCharge = unlockMapper.selectBicycleChargerule(String.valueOf(operatorId));

            //校验公交卡是否开户
            String s = "501,0";
            String ss = "501,1";
            int count2 = unlockMapper.selectCountUniversalCardByNowCardNo(cardNo);
            if (count2 !=1){
                ctx.channel().writeAndFlush(s);
                unlockMapper.insertBicycleCreditCardRecords(cardNo, new Date(), 1, -1);
            }else {
                Map<String ,Object> universalCardMap = unlockMapper.selectUniversalCardByNowCardNo(cardNo);
                Long universalCardId = (Long)universalCardMap.get("id");
                String riderId = (String)universalCardMap.get("rider_id");
                Integer cardType = (Integer)universalCardMap.get("card_type");

                //判断该卡有没有正在租车记录开始
                int count3 = unlockMapper.selectCountBicycleRentByRiderId(riderId);
                if (count3>0){
                    if (bicycleStatus==8){
                        //查找租车id
                        Map<String, Object> bicycleRentMap = unlockMapper.selectBicycleRentByRiderId(riderId);
                        Long rentId =(Long) bicycleRentMap.get("id");
                        String bicycle_noStr =(String) bicycleRentMap.get("bicycle_no");
                        if (!bicycle_noStr.equals(bicycleNo)){
                            log.error("临停车辆不同");
                            ctx.channel().writeAndFlush(s);
                        }

                        //临停解锁修改begin
                        int count4 =  unlockMapper.selectCountBicycleTemporaryStopId(bicycleId,rentId,riderId);
                        if (count4 == 1){
                            Long strBicycleTemporaryStopId = unlockMapper.selectBicycleTemporaryStopId(bicycleId, rentId, riderId);

                            unlockMapper.updateBicycle(new Date(),bicycleId);
                            unlockMapper.updateBicycleTemporaryStop(3,new Date(),strBicycleTemporaryStopId);

                            Integer putType =22;
                            //增加推送消息
                            //获取设备信息
                            Map<String, Object> pdaUseronlineMap = commonMapper.selectPdaUseronlineByRiderId(riderId);
                            if (pdaUseronlineMap==null ||pdaUseronlineMap.size()==0){
                                return false;
                            }
                            //deviceId 设备id,deviceType设备类型
                            String deviceId =(String) pdaUseronlineMap.get("deviceid");
                            Integer deviceType = (Integer)pdaUseronlineMap.get("device_type");
                            PushUtil.pushToSingle(deviceId, deviceType,"临停开车成功","开锁",0,22);

                            ctx.channel().writeAndFlush(ss);

                        }
                    }
                    //临停解锁修改end
                    unlockMapper.insertBicycleCreditCardRecords(cardNo,new Date(),1,1);
                    return false;
                }
                //判断该卡有没有正在租车记录结束

                if (bicycleStatus != 1){
                    log.error("自行车状态不正确");
                    return false;
                }
                //非团体卡押金小于200不能开锁
                if (cardType !=2){
                    int count5 = unlockMapper.selectCountA15riderForegift(riderId);
                    BigDecimal amount = new BigDecimal(0);
                    if (count5!=1){
                        amount=new BigDecimal(0);
                    }else {
                        BigDecimal foregiftAmount = unlockMapper.selectA15riderForegift(riderId);
                        amount=foregiftAmount;
                    }
                    if (amount.compareTo(new BigDecimal(200))==-1){
                        ctx.channel().writeAndFlush(s);
                        unlockMapper.insertBicycleCreditCardRecords(cardNo,new Date(),1,1);
                        return false;
                    }
                }
                //是不是新站点
                //获取自行车号、运营商id、自行车状态
                Integer type = unlockMapper.selectBicycleDocksiteType(dockSiteNo);
                if (StringUtils.isEmpty(type)){
                    log.error("站点类型不存在");
                    return false;
                }
                unlockMapper.insertBicycleRent(riderId,bicycleNo,new Date(),0,new Date(),dockSiteNo,universalCardId.toString(),operatorId,timeCharge,1,2,dockSiteId);
                if (type==1){
                    unlockMapper.updateBicycleDockSite(new Date(),dockSiteNo);
                }else {
                    unlockMapper.updateBicycleDockSiteTwo(new Date(),dockSiteNo);
                }
                unlockMapper.updateBicycleStatusAndDockSiteNo(lockNo, String.valueOf(operatorId));
                unlockMapper.insertBicycleCreditCardRecords(cardNo,new Date(),1,1);
                ctx.channel().writeAndFlush(ss);
            }
        }
        return false;
    }
}
